<template>
  <view v-if="show" class="uni-popup" :class="[`uni-popup--${type}`, `uni-popup--${position}`]">
    <view class="uni-popup__mask" @click="onTap"></view>
    <view class="uni-popup__wrapper" @click="onTap">
      <view class="uni-popup__content" @click.stop="onTap">
        <slot></slot>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'UniPopup',
  props: {
    // 开启动画
    animation: {
      type: Boolean,
      default: true
    },
    // 弹出层类型，可选值，top: 顶部弹出层；bottom：底部弹出层；center：全屏弹出层
    type: {
      type: String,
      default: 'center'
    },
    // 是否显示遮罩
    maskClick: {
      type: Boolean,
      default: true
    },
    // 控制弹出层是否显示
    show: {
      type: Boolean,
      default: false
    },
    // 遮罩颜色
    maskColor: {
      type: String,
      default: 'rgba(0, 0, 0, 0.4)'
    },
    // 弹出层位置
    position: {
      type: String,
      default: 'center'
    }
  },
  data() {
    return {}
  },
  watch: {
    show: {
      handler: function (newVal) {
        if (newVal) {
          this.open()
        } else {
          this.close()
        }
      },
      immediate: true
    }
  },
  methods: {
    open() {
      this.$emit('change', {
        show: true,
        type: this.type
      })
    },
    close() {
      this.$emit('change', {
        show: false,
        type: this.type
      })
    },
    onTap() {
      if (!this.maskClick) return
      this.close()
    }
  }
}
</script>

<style scoped>
.uni-popup {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 999;
}

.uni-popup__mask {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.4);
}

.uni-popup__wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.uni-popup__content {
  background-color: #fff;
  border-radius: 10rpx;
  max-width: 90%;
  max-height: 90%;
  overflow: hidden;
}

.uni-popup--center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.uni-popup--top {
  display: flex;
  align-items: flex-start;
  justify-content: center;
}

.uni-popup--bottom {
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.uni-popup--center .uni-popup__content {
  margin: 0;
  border-radius: 10rpx;
}

.uni-popup--top .uni-popup__content {
  margin-top: 0;
  border-radius: 0 0 10rpx 10rpx;
}

.uni-popup--bottom .uni-popup__content {
  margin-bottom: 0;
  border-radius: 10rpx 10rpx 0 0;
}
</style> 